﻿using System;
using System.Collections.Generic;
using System.Text;

namespace zijian666.AnyExtensions.Privates;

/// <summary>
/// 字符串违禁词替换器
/// </summary>
internal class ProfanityFilter
{
    public ProfanityFilter() { }

    public ProfanityFilter(Action<ProfanityFilter> option) => option(this);

    private readonly string[] _replaces = new string[char.MaxValue];

    private char[]? _invalidChars;

    public string this[char chr] { set => _replaces[chr] = value; }

    public ProfanityFilter Compile()
    {
        var chars = new List<char>();
        for (int i = 0; i < _replaces.Length; i++)
        {
            if (_replaces[i] is not null)
            {
                chars.Add((char)i);
            }
        }
        _invalidChars = [.. chars];
        return this;
    }

    public string Replace(string origin)
    {
        if (origin is null || _invalidChars is null or { Length: 0 })
        {
            return origin ?? "";
        }
        var index = origin.LastIndexOfAny(_invalidChars);

        if (index < 0)
        {
            return origin;
        }

        var buffer = new StringBuilder(origin);


        for (int i = index; i >= 0; i--)
        {
            var chr = buffer[i];
            var str = _replaces[chr];
            if (str is null)
            {
                continue;
            }
            if (str.Length == 1)
            {
                _ = buffer[i] = str[0];
            }
            else
            {
                _ = buffer.Remove(i, 1).Insert(i, str);
            }
        }


        return buffer.ToString();
    }
}
